package com.liy.framework.common.office.html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.HSSFColor.AUTOMATIC;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Excel2Html {
    static String[] bordesr = new String[]{"border-top:", "border-right:", "border-bottom:", "border-left:"};
    static String[] borderStyles = new String[]{"solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid", "solid", "solid", "solid", "solid"};

    public Excel2Html() {
    }

    public static String readExcelToHtml(String filePath, String htmlPositon, boolean isWithStyle) {
        InputStream is = null;
        String htmlExcel = null;

        try {
            File sourcefile = new File(filePath);
            is = new FileInputStream(sourcefile);
            Workbook wb = WorkbookFactory.create(is);
            if (wb instanceof XSSFWorkbook) {
                XSSFWorkbook xWb = (XSSFWorkbook)wb;
                htmlExcel = getExcelInfo(xWb, isWithStyle);
            } else if (wb instanceof HSSFWorkbook) {
                HSSFWorkbook hWb = (HSSFWorkbook)wb;
                htmlExcel = getExcelInfo(hWb, isWithStyle);
            }

            writeFile(htmlExcel, htmlPositon);
        } catch (Exception var16) {
            var16.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return htmlPositon;
    }

    private static String getExcelInfo(Workbook wb, boolean isWithStyle) {
        StringBuffer sb = new StringBuffer();
        Sheet sheet = wb.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        Map<String, String>[] map = getRowSpanColSpanMap(sheet);
        sb.append("<table style='border-collapse:collapse;' width='100%'>");
        Row row = null;
        Cell cell = null;

        for(int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; ++rowNum) {
            row = sheet.getRow(rowNum);
            if (row == null) {
                sb.append("<tr><td ><nobr> </nobr></td></tr>");
            } else {
                sb.append("<tr>");
                int lastColNum = row.getLastCellNum();

                for(int colNum = 0; colNum < lastColNum; ++colNum) {
                    cell = row.getCell(colNum);
                    if (cell == null) {
                        sb.append("<td> </td>");
                    } else {
                        String stringValue = getCellValue(cell);
                        if (map[0].containsKey(rowNum + "," + colNum)) {
                            String pointString = (String)map[0].get(rowNum + "," + colNum);
                            map[0].remove(rowNum + "," + colNum);
                            int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
                            int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
                            int rowSpan = bottomeRow - rowNum + 1;
                            int colSpan = bottomeCol - colNum + 1;
                            sb.append("<td rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
                        } else {
                            if (map[1].containsKey(rowNum + "," + colNum)) {
                                map[1].remove(rowNum + "," + colNum);
                                continue;
                            }

                            sb.append("<td ");
                        }

                        if (isWithStyle) {
                            dealExcelStyle(wb, sheet, cell, sb);
                        }

                        sb.append("><span>");
                        if (stringValue != null && !"".equals(stringValue.trim())) {
                            sb.append(stringValue.replace(String.valueOf(' '), " "));
                        } else {
                            sb.append("   ");
                        }

                        sb.append("</span></td>");
                    }
                }

                sb.append("</tr>");
            }
        }

        sb.append("</table>");
        return sb.toString();
    }

    private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
        Map<String, String> map0 = new HashMap();
        Map<String, String> map1 = new HashMap();
        int mergedNum = sheet.getNumMergedRegions();
        CellRangeAddress range = null;

        for(int i = 0; i < mergedNum; ++i) {
            range = sheet.getMergedRegion(i);
            int topRow = range.getFirstRow();
            int topCol = range.getFirstColumn();
            int bottomRow = range.getLastRow();
            int bottomCol = range.getLastColumn();
            map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);

            for(int tempRow = topRow; tempRow <= bottomRow; ++tempRow) {
                for(int tempCol = topCol; tempCol <= bottomCol; ++tempCol) {
                    map1.put(tempRow + "," + tempCol, "");
                }
            }

            map1.remove(topRow + "," + topCol);
        }

        Map[] map = new Map[]{map0, map1};
        return map;
    }

    private static String getCellValue(Cell cell) {
        new String();
        String result;
        switch(cell.getCellType()) {
            case 0:
                SimpleDateFormat sdf;
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    sdf = null;
                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else {
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }

                    Date date = cell.getDateCellValue();
                    result = sdf.format(date);
                } else if (cell.getCellStyle().getDataFormat() == 58) {
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                    double value = cell.getNumericCellValue();
                    Date date = DateUtil.getJavaDate(value);
                    result = sdf.format(date);
                } else {
                    double value = cell.getNumericCellValue();
                    CellStyle style = cell.getCellStyle();
                    DecimalFormat format = new DecimalFormat();
                    String temp = style.getDataFormatString();
                    if (temp.equals("General")) {
                        format.applyPattern("#");
                    }

                    result = format.format(value);
                }
                break;
            case 1:
                result = cell.getRichStringCellValue().toString();
                break;
            case 2:
            default:
                result = "";
                break;
            case 3:
                result = "";
        }

        return result;
    }

    private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb) {
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle != null) {
            short alignment = cellStyle.getAlignment();
            short verticalAlignment = cellStyle.getVerticalAlignment();
            sb.append("valign='" + convertVerticalAlignToHtml(verticalAlignment) + "' ");
            short boldWeight;
            if (wb instanceof XSSFWorkbook) {
                XSSFFont xf = ((XSSFCellStyle)cellStyle).getFont();
                boldWeight = xf.getBoldweight();
                String align = convertAlignToHtml(alignment);
                sb.append("style='");
                sb.append("font-weight:" + boldWeight + ";");
                sb.append("font-size: " + xf.getFontHeight() / 2 + "%;");
                int columnWidth = (int)sheet.getColumnWidthInPixels(cell.getColumnIndex());
                sb.append("word-wrap:break-word;word-break:break-all;");
                sb.append("width:" + columnWidth + "px;");
                sb.append("text-align:" + align + ";");
                XSSFColor xc = xf.getXSSFColor();
                if (xc != null && !"".equals(xc)) {
                    sb.append("color:#" + xc.getARGBHex().substring(2) + ";");
                }

                XSSFColor bgColor = (XSSFColor)cellStyle.getFillForegroundColorColor();
                if (bgColor != null && !"".equals(bgColor)) {
                    sb.append("background-color:#" + bgColor.getARGBHex().substring(2) + ";");
                }

                sb.append(getBorderStyle(0, cellStyle.getBorderTop(), ((XSSFCellStyle)cellStyle).getTopBorderXSSFColor()));
                sb.append(getBorderStyle(1, cellStyle.getBorderRight(), ((XSSFCellStyle)cellStyle).getRightBorderXSSFColor()));
                sb.append(getBorderStyle(2, cellStyle.getBorderBottom(), ((XSSFCellStyle)cellStyle).getBottomBorderXSSFColor()));
                sb.append(getBorderStyle(3, cellStyle.getBorderLeft(), ((XSSFCellStyle)cellStyle).getLeftBorderXSSFColor()));
            } else if (wb instanceof HSSFWorkbook) {
                HSSFFont hf = ((HSSFCellStyle)cellStyle).getFont(wb);
                boldWeight = hf.getBoldweight();
                short fontColor = hf.getColor();
                sb.append("style='");
                HSSFPalette palette = ((HSSFWorkbook)wb).getCustomPalette();
                HSSFColor hc = palette.getColor(fontColor);
                sb.append("font-weight:" + boldWeight + ";");
                sb.append("font-size: " + hf.getFontHeight() / 2 + "%;");
                String align = convertAlignToHtml(alignment);
                sb.append("text-align:" + align + ";");
                String fontColorStr = convertToStardColor(hc);
                if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
                    sb.append("color:" + fontColorStr + ";");
                }

                int columnWidth = (int)sheet.getColumnWidthInPixels(cell.getColumnIndex());
                sb.append("width:" + columnWidth + "px;");
                sb.append("word-wrap:break-word;word-break:break-all;");
                short bgColor = cellStyle.getFillForegroundColor();
                hc = palette.getColor(bgColor);
                String bgColorStr = convertToStardColor(hc);
                if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
                    sb.append("background-color:" + bgColorStr + ";");
                }

                sb.append(getBorderStyle(palette, 0, cellStyle.getBorderTop(), cellStyle.getTopBorderColor()));
                sb.append(getBorderStyle(palette, 1, cellStyle.getBorderRight(), cellStyle.getRightBorderColor()));
                sb.append(getBorderStyle(palette, 3, cellStyle.getBorderLeft(), cellStyle.getLeftBorderColor()));
                sb.append(getBorderStyle(palette, 2, cellStyle.getBorderBottom(), cellStyle.getBottomBorderColor()));
            }

            sb.append("' ");
        }

    }

    private static String convertAlignToHtml(short alignment) {
        String align = "center";
        switch(alignment) {
            case 1:
                align = "left";
                break;
            case 2:
                align = "center";
                break;
            case 3:
                align = "right";
        }

        return align;
    }

    private static String convertVerticalAlignToHtml(short verticalAlignment) {
        String valign = "middle";
        switch(verticalAlignment) {
            case 0:
                valign = "top";
                break;
            case 1:
                valign = "center";
                break;
            case 2:
                valign = "bottom";
        }

        return valign;
    }

    private static String convertToStardColor(HSSFColor hc) {
        StringBuffer sb = new StringBuffer("");
        if (hc != null) {
            if (AUTOMATIC.index == hc.getIndex()) {
                return null;
            }

            sb.append("#");

            for(int i = 0; i < hc.getTriplet().length; ++i) {
                sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
            }
        }

        return sb.toString();
    }

    private static String fillWithZero(String str) {
        return str != null && str.length() < 2 ? "0" + str : str;
    }

    private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
        if (s == 0) {
            return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
        } else {
            String borderColorStr = convertToStardColor(palette.getColor(t));
            borderColorStr = borderColorStr != null && borderColorStr.length() >= 1 ? borderColorStr : "#000000";
            return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
        }
    }

    private static String getBorderStyle(int b, short s, XSSFColor xc) {
        if (s == 0) {
            return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
        } else if (xc != null && !"".equals(xc)) {
            String borderColorStr = xc.getARGBHex();
            borderColorStr = borderColorStr != null && borderColorStr.length() >= 1 ? borderColorStr.substring(2) : "#000000";
            return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
        } else {
            return "";
        }
    }

    private static void writeFile(String content, String htmlPath) {
        File file2 = new File(htmlPath);
        StringBuilder sb = new StringBuilder();

        try {
            file2.createNewFile();
            sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>Html Test</title></head><body>");
            sb.append("<div>");
            sb.append(content);
            sb.append("</div>");
            sb.append("</body></html>");
            PrintStream printStream = new PrintStream(new FileOutputStream(file2));
            printStream.println(new String(sb.toString().getBytes("UTF-8"), "UTF-8"));
        } catch (IOException var5) {
            var5.printStackTrace();
        }

    }
}
